import { Component, OnInit, Input } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-userinfo-component',
  templateUrl: './userinfo-component.component.html',
  styleUrls: ['./userinfo-component.component.less']
})
export class UserInfoComponent implements OnInit {

  validateForm: FormGroup;
  @Input() isregister: boolean;

  constructor(private fb: FormBuilder) {
  }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      id: [{ value: 'asdasdas-asdasddsfd-dfgdfg-sdfssdf', disabled: true }, [Validators.required]],
      account: [null, [Validators.required]],
      nickname: [null, [Validators.required]],
      password: [null, [Validators.required]],
      checkPassword: [null, [Validators.required, this.confirmationValidator]],
      phoneNumberPrefix: ['+86'],
      phoneNumber: [null, [Validators.required]],
      idnumber: [null, [Validators.required]],
      capitalstate: ['jack', [Validators.required]],
      accountstate: ['jack', [Validators.required]],
      belongto: ['jack', [Validators.required]],
    });
    if (this.isregister) {
      this.validateForm.removeControl('id');
      this.validateForm.removeControl('accountstate');
    } else {
      this.validateForm.removeControl('account');
      this.validateForm.removeControl('belongto');
    }
  }

  submitForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
  }

  updateConfirmValidator(): void {
    /** wait for refresh value */
    Promise.resolve().then(() => this.validateForm.controls.checkPassword.updateValueAndValidity());
  }

  confirmationValidator = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return { required: true };
    } else if (control.value !== this.validateForm.controls.password.value) {
      return { confirm: true, error: true };
    }
  }

  getCaptcha(e: MouseEvent): void {
    e.preventDefault();
  }

}
